#include "LoginTask.h"

LoginTask::LoginTask(char *body, int len, int socketfd) : BaseTask::BaseTask(body, len, socketfd)
{
}

LoginTask::~LoginTask()
{
}

void LoginTask::work(Buffer*buffer)
{
    LOGIN_REQ login_req = {0};
    HEAD head = {0};
    char send_buffer[1024] = {0};
    memcpy(&login_req, m_body, m_len);

    // 校验用户名和密码
    bool is_login = false;
    for (auto &e : CData::user_data)
    {
        if (e.getId() == login_req.id && strcmp(e.getPasswd(), login_req.password) == 0)
        {
            is_login = true;
            break;
        }
    }
    LOGIN_RESP login_resp = {0};
    login_resp.id = login_req.id;
    if (is_login)
    {
        CData::user[login_req.id] = m_socketfd; // 记录该用户上线
        //  响应数据到客户端
        login_resp.status = 0;
    }
    else if (!is_login)
    {
        // 登录未成功，返回对应的响应
        login_resp.status = 1;
    }
    bzero(&head, sizeof(HEAD));
    bzero(send_buffer, sizeof(send_buffer));

    head.service_type = LOGIN;
    head.data_len = sizeof(login_resp);

    memcpy(send_buffer, &head, sizeof(HEAD));
    memcpy(send_buffer + sizeof(HEAD), &login_resp, head.data_len);
    buffer->appendString(send_buffer, sizeof(HEAD) + head.data_len);
    //int len = write(m_socketfd, send_buffer, sizeof(HEAD) + head.data_len);
    cout<<"发送登陆响应"<<endl;
}
